package com.foogui.primary.communication;

import java.util.concurrent.Semaphore;

public class SemaphoreDemo {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                System.out.println(Thread.currentThread().getName()+"号线程到达了停车场");
                if (semaphore.availablePermits()==0) System.out.println(Thread.currentThread().getName()+"号线程暂时没有停车位，请等待");
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName()+"号线程进入了停车场停车");
                    Thread.sleep(1000);
                    System.out.println(Thread.currentThread().getName()+"号线程停了1秒，驶出了停车场");
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }finally{
                    semaphore.release();
                }
            },i+"").start();
        }
    }
}
